package com.shinewind.home.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.shinewind.common.constant.messageConstant;
import com.shinewind.home.service.ICartService;
import com.shinewind.pojo.dto.CartGoodDto;
import com.shinewind.pojo.entity.Cart;
import com.shinewind.pojo.result.Result;
import com.shinewind.pojo.vo.CartVo;
import com.shinewind.pojo.vo.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/index")
@Api(value = "购物车接口",description = "用于实现购物车列表的显示")
public class CartController {
    @Autowired
    private ICartService iCartService;

    @GetMapping("/model/cart/list/{uId}")
    @ApiOperation(value = "购物车信息列表",notes = "购物车商品",response = Result.class)
    public PageVo<CartVo> getCartList(@PathVariable("uId") String uId){
        List<Cart> cartList = iCartService.getCartList(uId);
        List<CartVo> cartVoList = cartList.stream().map(cart -> {
            CartVo cartVo = CartVo.builder().build();
            BeanUtils.copyProperties(cart,cartVo);
            cartVo.setKey(cart.getCId());
            return cartVo;
        }).collect(Collectors.toList());
        return new PageVo<CartVo>(cartVoList, BooleanUtil.isTrue(cartVoList.size()>0),
                messageConstant.QUERY_SUCCESS, cartVoList.size());
    }

    @PostMapping("/model/add/good")
    @ApiOperation(value = "添加商品到购物车表",notes = "添加商品",response = Result.class)
    public Result addCartGood(@RequestBody CartGoodDto cartGoodDto){
        System.out.println(cartGoodDto);
        //接受前端加购的Dto对象
        Boolean flag = iCartService.saveCartGoodIfNotExist(cartGoodDto);
        if(flag)
            return Result.success(true,
                    messageConstant.INSERT_SUCCESS);
        else
            return Result.fail(false,messageConstant.INSERT_ERROR);
    }

    @DeleteMapping("/model/delete/good/{uId}/{cId}")
    @ApiOperation(value = "从购物车删除商品",notes = "购物车删除商品",response = Result.class)
    public Result deleteCartGood(@PathVariable("uId") String uId,@PathVariable("cId") String cId){
        Boolean flag = iCartService.deleteCartGoodBycId(uId,cId);
        if(flag)
            return Result.success(true,
                    messageConstant.DELETE_SUCCESS);
        else
            return Result.fail(false,messageConstant.DELETE_ERROR);
    }
}
